<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-table :data="rolesList" style="width: 100%" border>
      <el-table-column type="expand" label="#" width="180">
        <template slot-scope="scope">
          <!-- 第一次循环 -->
          <el-row
            v-for="(value1 , index1 ) in scope.row.children"
            v-bind:key="value1.id"
            :class="['bdbottom',index1 == 0 ? 'bdtop':'']"
          >
            <el-col :span="6">
              <el-tag closable @close="closeMenu(scope.row,value1)">{{value1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 在第二列开启第二次循环 -->
            <el-col :span="18">
              <el-row
                v-for="(value2 ) in value1.children"
                v-bind:key="value2.id"
                :class="['bdbottom']"
              >
                <el-col :span="6">
                  <el-tag
                    type="success"
                    closable
                    @close="closeMenu(scope.row,value2)"
                  >{{value2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 然后再次在第二列开启第三轮循环  需要将这个用户的rid和需要删除的id都传递给函数-->
                <el-col :span="18">
                  <el-tag
                    type="warning"
                    v-for="value3 in value2.children"
                    v-bind:key="value3.id"
                    closable
                    @close="closeMenu(scope.row,value3)"
                  >{{value3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" label="#" width="180"></el-table-column>
      <el-table-column prop="roleName" label="角色名称" width="180"></el-table-column>
      <el-table-column prop="roleDesc" label="角色描述" width="180"></el-table-column>
      <el-table-column prop label="操作">
        <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRight(scope.row)"
            >权限分配</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 权限分配弹框 -->
    <el-dialog title="分配权限" :visible.sync="dialogVisible" width="100%" @close='setRightDialogClosed'>
      <!-- 树形的表格 -->
      <el-tree
        :data='roleSaveEditData'
        show-checkbox
        :default-expand-all='true'
        node-key="id"
        :default-expanded-keys="[2, 3]"
        :default-checked-keys="defkeys" 
        :props="defaultProps"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false;">取 消</el-button>
        <el-button type="primary" @click="roleSaveEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      roleID:'',
      rolesList: [],
      dialogVisible: false,
      roleSaveEditData: [],
      defkeys:[],
      defaultProps:{
        children:'children',
        label:'authName',
        
      }
    }
  },
  methods: {
    async getRolesList() {
      let { data: res } = await this.axios.get('roles')
      // console.log(res)
      if (res.meta.status != 200) return this.$message.error('请求错误')
      this.$message.success('请求成功')
      this.rolesList = res.data
    },

    async closeMenu(val, role) {
      console.log(val, role)

      //弹出删除的提示确认按钮
      let getconfirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      // console.log(getconfirm)
      if (getconfirm != 'confirm') return this.$message.error('已经取消该操作')
      let { data: res } = await this.axios.delete(`roles/${val.id}/rights/${role.id}`)
      if (res.meta.status != 200) {
        this.$message.error('操作失败')
      }
      this.$message.success('权限已经取消')
      //  权限取消成功后重新将数据赋值给视图
      // console.log(res.data);
      //将全选直接赋值给对应的角色就行这样是局部刷新
      val.children = res.data
      // }
    },
    // 设置权限
    async showSetRight(role) {
      this.roleID=role.id
      
      // 进入后先获取所有的数据使用axios发起请求
      let { data: res } = await this.axios.get('rights/tree')
      if (res.meta.status != 200) return this.$message.error('权限获取错误')
      // 接下来权限全部获取 然后需要将数据进行存储后进行数据渲染
      this.roleSaveEditData = res.data
      console.log(this.roleSaveEditData)
          //调用数组获取id
          //将需要的数据传递过去 第一个是用户的id 第二个是一个空数组 
      this.getLeafKeys(role,this.defkeys)
      this.dialogVisible = true
      
    },
    // 接下来将所有用户的权限进行获取并根据三级节点的权限的id去存储一个数组
    getLeafKeys(node,arr){
      if(!node.children) {
       return  arr.push(node.id)
      };
      node.children.forEach(item=>{
        this.getLeafKeys(item,arr)
      })
    },
    // 监听去权限按钮的关闭事件
    setRightDialogClosed(){
      // 点击后需要将数据清空
      this.defkeys=[];
     
    },
    // 点击为角色分配权限
    async roleSaveEdit() {
      // this.dialogVisible = false;
      const keys=[...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()]
      // console.log(keys);
      const idstr=keys.join(',');
      // 然后发起ajax请求将权限提交 roles/:roleId/rights
      let {data:res}=await this.axios.post(`roles/${this.roleID}/rights`,{
        rids:idstr
      })
      if(res.meta.status!=200) return this.$message.error('提交失败');
      this.$message.success('修改成功')
      this.getRolesList();
       this.dialogVisible = false;
    }
  },
  created() {
    this.getRolesList()
  }
}
</script>


<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin-right: 20px;
}
.el-row,
.el-col {
  margin-bottom: 5px;
}
.bdtop {
  border-top: 1px solid #ccc;
}
.bdbottom {
  border-bottom: 1px solid #ccc;
}
</style>
